package by.alex.dzeshko.facebooksuperclient.async;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.text.TextUtils;
import android.util.Log;
import by.alex.dzeshko.facebooksuperclient.R;
import by.alex.dzeshko.facebooksuperclient.async.common.CommonAsyncTask;
import by.alex.dzeshko.facebooksuperclient.async.common.ParamCallback;
import by.alex.dzeshko.facebooksuperclient.http.HttpManager;
import by.alex.dzeshko.facebooksuperclient.http.RequestBuilder;
import by.alex.dzeshko.facebooksuperclient.http.RequestBuilder.Type;
import by.alex.dzeshko.facebooksuperclient.oauth.FBOAuthHelper;

public class NewPostTask extends CommonAsyncTask<JSONObject> {
	
	private static final String MESSAGE = "message";
	private static final String LOG_TAG = "NewPostTask";
	private String url, message;
	
	public NewPostTask(ParamCallback<JSONObject> paramCallback) {
		super(paramCallback);
	}	
	
	@Override
	protected JSONObject doInBackground(RequestBuilder... params) {

		url = params[0].getUrl();
		if(params[0].getType()==Type.POST){
				ArrayList<BasicNameValuePair> data = new ArrayList<BasicNameValuePair>();
				data.add(new BasicNameValuePair(FBOAuthHelper.ACCESS_TOKEN, FBOAuthHelper.getToken()));
				if(params[0].getMessge()!=null){
				message = params[0].getMessge();
				data.add(new BasicNameValuePair(MESSAGE, message));
				}
				String source;
				try {
					source = HttpManager.getInstance().postRequest(url, data);
					return convert(source);
				} catch (ClientProtocolException e) {
					this.e = e;
				} catch (IOException e) {
					this.e = e;
				} catch (Exception e) {
					this.e = e;
				}
			return null;
		}
		else if(params[0].getType()==Type.DELETE){
			
			Object source;
			try {
				source = HttpManager.getInstance().deleteRequest(url);
				return convert(source);
			} catch (ClientProtocolException e) {
				this.e = e;
			} catch (IOException e) {
				this.e = e;
			} catch (Exception e) {
				this.e = e;
			}
			return null;
		}
		else return null;
	}


	@Override
	public JSONObject convert(Object source) throws Exception {
		Log.d(LOG_TAG, "source="+source);
		if (source == null) {
			Log.e(LOG_TAG, "convert source null");
			return null;
		}
		if (source instanceof Exception)
			throw (Exception) source;
		String s = null;
		if (source instanceof String)
			s = (String) source;
		if(s.contains("error")){
			return new JSONObject(s);
		} else if(s.contains("id")){
			return new JSONObject(s);
		} else if(s.contains("true")){
			//return new JSONObject("{\"value\":\""+source+"\"}");
			return new JSONObject("{\"value\":\"+source+\"}");
		} else {
			Log.d("value", s);
			return new JSONObject("{\"value\":\"+source+\"}");
		}
	}
	
}

